﻿using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.BasicData_UI.BasicData.Select;
using B.MESUI.Login.EquipmentManagement.DeviceLedgerService;
using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.EquipmentManagement.Model;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Standard;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static B.MESUI.Login.BasicData_UI.WorkStation.AddStationForm;

namespace B.MESUI.Login.BasicData_UI.WorkStation
{
    public partial class GetStationForm : DevExpress.XtraEditors.XtraForm
    {

        // 用于保存产线名称和ID的映射
        private Dictionary<string, string> lineNameIdMap = new Dictionary<string, string>();
        private readonly DeviceGridPanel devicePanel;
        private readonly HttpClient httpClient;
        public GetStationForm()
        {
            InitializeComponent();

           
            // 1. 创建控件实例
            devicePanel = new DeviceGridPanel();
            devicePanel.Dock = DockStyle.Fill;

            // 2. 加入到主窗体的某个Panel或直接加到this.Controls
            this.Controls.Add(devicePanel);

            // 3. 生成动态查询控件（如果没有查询就可以直接隐藏了）
            GenerateDeviceSearchControls();

            // 4. 绑定事件
            devicePanel.AddClicked += (s, e) =>
            { /* 新增逻辑 */
                AddStationForm addStationForm = new AddStationForm();
                
                addStationForm.StationLoad += () =>
                {
                    // 刷新数据
                    FlushData();
                };
                addStationForm.ShowDialog();
            };
            devicePanel.ExportClicked += async (s, e) => { /* 导出逻辑 */
                // 调用后端导出接口，假设接口为 /api/WorkShop/Export
                string url1 = "http://39.103.49.30:9982/api/WorkStation/Export/export";
                using (HttpClient client = new HttpClient())
                {
                    try
                    {
                        var response = await client.GetAsync(url1);
                        if (response.IsSuccessStatusCode)
                        {
                            var bytes = await response.Content.ReadAsByteArrayAsync();
                            using (SaveFileDialog sfd = new SaveFileDialog())
                            {
                                sfd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                                sfd.FileName = "车间信息导出.xlsx";
                                if (sfd.ShowDialog() == DialogResult.OK)
                                {
                                    System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                    MessageBox.Show("导出成功！");
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("导出失败！");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出异常：" + ex.Message);
                    }
                }
            };
            devicePanel.DeleteClicked += async (s, e) =>
            {
                /* 删除逻辑 */
                var ids = devicePanel.GetSelectedIdsString();

                if (ids.Length == 0) { MessageBox.Show("请选择要删除的数据！！！"); }
                else
                {
                    using (HttpClient client = new HttpClient())
                    {
                        var response = await client.DeleteAsync($"http://39.103.49.30:9982/api/WorkStation/WorkStationDeleteList?Ids={ids}");
                        if (response.IsSuccessStatusCode)
                        {
                            MessageBox.Show("删除成功！");
                            FlushData(); // 刷新数据
                        }
                        else
                        {
                            MessageBox.Show("删除失败！");
                        }
                    }
                }
            };
            //编辑事件
            devicePanel.EditClicked += (s, e) => { MessageBox.Show("你点击的ID是：" + e);
         
                GetStationDTO getStationDTO = new GetStationDTO();

                var selectedRow = devicePanel.gridView.GetFocusedRow();
                getStationDTO= selectedRow as GetStationDTO;

                if (selectedRow == null)
                {
                    MessageBox.Show("请选择一行数据进行编辑！");
                    return;
                }

                //把id传入修改页面
                UpdateStationForm updateStationForm = new UpdateStationForm(getStationDTO);
                updateStationForm.updateload += () =>
                {
                    // 刷新数据
                    FlushData();
                };
                updateStationForm.ShowDialog();
            };
            // 查询事件
            devicePanel.SearchClicked += async (s, e) =>
            {
                // 获取查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 重置到第一页进行查询
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize, searchConditions);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };
            // 重置事件
            devicePanel.ResetClicked += async (s, e) =>
            {
                // 重置查询条件
                devicePanel.ResetSearchConditions();
                // 重新加载第一页数据
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };
            // 5. 分页事件
            devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            {
                // 获取当前查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 这里调用你的后端API
                var result = await GetDeviceTypeListAsync(pageIndex, pageSize, searchConditions); // 你的API
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
            };
        }


        //添加查询控件方法
        private void GenerateDeviceSearchControls()
        {
            // 字段名和控件类型的映射（后端定义）
            var fieldMappings = new Dictionary<string, SearchControlType>
            {
                /*支持的控件类型：
               - SearchControlType.TextBox: 文本框
               - SearchControlType.ComboBox: 下拉框
               - SearchControlType.DateEdit: 日期选择器
               - SearchControlType.CheckBox: 复选框*/
                //示例前面查询的字段名，后面是控件类型：{ "WORKSTATION_CODE", SearchControlType.TextBox },
                { "WORKSTATION_CODE", SearchControlType.TextBox },
                { "WORKSTATION_NAME", SearchControlType.TextBox },
                { "LINE_ID", SearchControlType.ComboBox },
            };

            // 显示名称映射（可选）
            var displayNames = new Dictionary<string, string>
            {
                //也就是修改查询显示的名称{ "Name", "设备名称" },
                { "WORKSTATION_CODE", "工位编码" },
                { "WORKSTATION_NAME", "工位名称" },
                { "LINE_ID", "产线名称" },
            };


            string url = $"http://39.103.49.30:9982/api/ProjectLine/GetProductionLine";
            using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    var respStr = response.Content.ReadAsStringAsync().Result;
                    var result = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult<List<SelectLineDTO>>>(respStr);
                    if (result != null && result.ResultData != null)
                    {
                        // 清空之前的映射
                        lineNameIdMap.Clear();
                        // 遍历结果并填充映射
                        foreach (var item in result.ResultData)
                        {
                            lineNameIdMap[item.LINE_NAME] = item.ID;
                        }
                        var comboOptions1 = new Dictionary<string, List<string>>
                        {
                            { "LINE_ID", result.ResultData.Select(x => x.LINE_NAME).ToList() }
                        };
                        //查询产线
                        //下拉显示名称 查ID
                        comboOptions1[displayNames["LINE_ID"]] = result.ResultData.Select(x => x.LINE_NAME).ToList();
                        //调用动态生成查询控件方法
                        devicePanel.GenerateSearchControls(fieldMappings, displayNames, comboOptions1);
                    }
                    else
                    {
                        XtraMessageBox.Show("未找到产线数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            
            //   // 下拉框选项（可选）
            //   var comboOptions = new Dictionary<string, List<string>>
            //   {
            //       //你的下拉里面的内容，左侧选择一个你添加的下拉名，手动就直接写，动态的就直接直接抓取给值就行了{ "State", new List<string> { "正常", "维修中", "报废", "闲置" } }
            //       //把下拉框的选项
            //       //动态 
            //   { "LINE_ID", new List<string>{  "正常", "维修中", "报废", "闲置"} }
            //};

        }
        /// <summary>
        /// 绑定数据、隐藏指定列、设置列名方法
        /// </summary>
        private void BindDataSetColumns(List<GetStationDTO> data)
        {
            // 需要隐藏的列名
            var hideColumnNames = new[] { "IsDeleted", "AnotherColumn","Id","linE_ID" };
        
            // 列名映射
            var columnCaptions = new Dictionary<string, string>
                    {
                        { "id", "编号" },
                        { "workstatioN_CODE", "编码" },
                        { "workstatioN_NAME", "名称" },
                         { "linE_NAME", "产线名称" },
                        { "workstatioN_DESCRIPTION", "描述" },
                        { "createdusername", "创建人" },
                        { "updatedusername", "更新人" },
                        { "createtime", "创建时间" },
                        { "updatetime", "更新时间" },
                        // 其他字段...
                        //隐藏字段...

                    };
        
            devicePanel.SetDataSource(data);
            foreach (var colName in hideColumnNames)
            {
                var col = devicePanel.gridView.Columns[colName];
                if (col != null)
                    col.Visible = false;
            }
            devicePanel.SetColumnCaptions(columnCaptions);
        }
        // 获取显示值方法，实际根据你的后端API来写
        private async Task<(List<GetStationDTO> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize, Dictionary<string, object> searchConditions = null)
        {
            // 调用后端接口，返回数据和总数
            using (var client = new HttpClient())
            {
                // 构建查询参数
                var queryParams = new List<string>
                {
                    $"PageIndex={pageIndex}",
                    $"PageSize={pageSize}"
                };
        
                // 添加查询条件
                if (searchConditions != null && searchConditions.Count > 0)
                {
                    foreach (var condition in searchConditions)
                    {
                        if (condition.Value != null)
                        {
                            string value = condition.Value.ToString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                // 根据值类型进行不同的处理
                                if (condition.Value is DateTime dateTime)
                                {
                                    value = dateTime.ToString("yyyy-MM-dd");
                                }
                                else if (condition.Value is bool boolValue)
                                {
                                    value = boolValue.ToString().ToLower();
                                }
        
                                queryParams.Add($"{condition.Key}={(value)}");
                            }
                        }
                    }
                }
                string queryString = string.Join("&", queryParams);
                //改成自己的接口
                string url = $"http://39.103.49.30:9982/api/WorkStation/GetPageWorkStation?{queryString}";
                //替换为自己的传值方式"Get","Post","Put","Delete"
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                //替换为你自己的数据模型
                var result = JsonConvert.DeserializeObject<ApiPaging<GetStationDTO>>(json);
                foreach (var item in result.PageDatas)
                {
                    item.Id = item.id; // 这里假设你需要将id字段赋值给Id属性
                }
                return (result.PageDatas, result.TotalCount);
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void FlushData()
        {
            // 首次加载第一页
            var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
            BindDataSetColumns(result.Data);
            devicePanel.SetPageInfo(1, 20, result.TotalCount);
        }

        private void GetStation_Load(object sender, EventArgs e)
        {
            FlushData();
        }

    }
}